import {isRelogin} from "@/api/request";

const {createRouter, createWebHistory} = require('vue-router')
const Home = () => import('@/views/Home')
import {getToken} from '@/utils/auth'
import useUserStore from "@/store/modules/user";

export const routes = [
    {
        path: '/login',
        name: 'login',
        component: () => import('@/views/Login')
    },
    {
        path: '/',
        name: 'default',
        component: Home,
        meta: {requireAuth: true}
    },
    {
        path: '/index',
        name: 'index',
        component: Home,
        meta: {requireAuth: true}
    },
    {
        path: '/document/:docId/:type',
        name: 'document',
        component: Home,
        props: true,
        meta: {requireAuth: true}
    },
    {
        path: '/shareSpace',
        name: 'shareSpace',
        component: Home,
        // meta: { requireAuth: true }
    },
    {
        path: '/solution',
        name: 'solution',
        component: Home,
        meta: {requireAuth: true}
    },
    {
        path: '/solutionTab',
        name: 'solutionTab',
        component: Home,
        meta: {requireAuth: true}
    },
    {
        path: '/personalData',
        name: 'personalData',
        component: () => import('@/views/PersonalData'),
        meta: {requireAuth: true}
    },
    {
        path: '/404',
        name: '404',
        component: () => import("@/views/NotFound")
    },
    {
        path: "/DetailPreview/:docId/:type",
        name: "DetailPreview",
        props: true,
        component: () => import("@/components/homeShareSpace/DetailPreview")
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: routes,
})

router.beforeEach((to, _from, next) => {
    //进行判断，如果to路径没有匹配到现有的任何一个路由
    //作用：当to的路由为空时不跳转，同时当from的路由也为空时，则跳转到404页面
    if (to.matched.length === 0) {
        //这里打印输出
        next('/404');
    } else if (to.meta.requireAuth && !getToken()) {
        // 如果to的路由名称不为空，则进行跳转
        router.replace({
            name: 'login',
            query: {redirect: to.name}
        })
        next()
    } else if (useUserStore().roles.length === 0 && to.path !== '/login'&& getToken()) {
        isRelogin.show = true
        useUserStore().getInfo().then(() => {
            isRelogin.show = false
            next()
        }).catch(() => {
            useUserStore()
                .logout()
                .then(() => {
                    router.replace({
                        name: 'login',
                        query: {redirect: to.name}
                    })
                })
        })
    } else {
        next()
    }
})

export default router